本文共 37276 字,大约阅读时间需要 124 分钟。
public class RandomUtils { //当前时间 + 随机数 public static String createActive(){ return getTime()+Integer.toHexString(new Random().nextInt(900)+100); } private static String getTime(){ return new SimpleDateFormat("yyyyMMddHHmmssSSS").format(Calendar.getInstance().getTime()); } //生成订单编号 public static String createOrderId(){ return getTime(); }}
public class DruidUtils { private static DruidDataSource dataSource; static { Properties properties = new Properties(); InputStream is = DruidUtils.class.getClassLoader().getResourceAsStream("druid.properties"); try { properties.load(is); dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("初始化连接池失败", e); } } public static DataSource getDataSource() { return dataSource; }}
public class EmailUtils { public static void sendEmail(User user){ //发送方 String myAccount = "renjie9283@163.com"; //授权码,需要到自己邮箱去生成 String myPass = "cq1701"; //发件人 邮箱的 SMTP 服务器地址,如果是qq邮箱则改成smtp.qq.com String SMTPHost = "smtp.163.com"; //组成 properties Properties prop = new Properties(); prop.setProperty("mail.transport.protocol", "smtp");//设置协议类型 prop.setProperty("mail.smtp.host", SMTPHost);//定义发件人的邮箱服务器地址 prop.setProperty("mail.smtp.auth", "true");//设置请求验证 //1.Session对象 创建会话 用于和邮箱服务器进行交互 Session session = Session.getDefaultInstance(prop); //设置debug模式 可以查看详细发送信息 可略 session.setDebug(true); //2.创建方法 用来组成一封完整的邮件 //参数 session(参数配置), myAccount 发送方 , user.getEmail() 接收方 MimeMessage message = createMsg(session,myAccount,user); //4.利用Transport 发送邮件 try { Transport tran = session.getTransport(); //连接服务器 确认发送方 是否授权 tran.connect(myAccount, myPass); //发送邮件 将message 对象 传给 Transport 对象 将邮件发送出去 //参数1 要发的内容 参数2 要给哪些人发 //message.getAllRecipients() 获取到所有的收件人 | 抄送 | 密送 tran.sendMessage(message, message.getAllRecipients()); //关闭连接 tran.close(); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static MimeMessage createMsg(Session session, String myAccount, User user) { //使用session对象 获取待发送的邮件信息 MimeMessage message = new MimeMessage(session); //3.设置发件人 收件人 标题 邮件内容 附件 发送时间等等 try { //3.1发件人 from message.setFrom(new InternetAddress(myAccount, "小米", "utf-8")); //3.2收件人 to 支持可以添加多个收件人 | 抄送 | 密送 如果想要发送给多个人 可以重复下面代码多次 /* * MimeMessage.RecipientType.TO 发送 * MimeMessage.RecipientType.CC 抄送 * MimeMessage.RecipientType.BCC 密送 * */ message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(user.getEmail(), user.getUsername(), "utf-8")); //3.3生成邮件主题 message.setSubject("小米商城账号激活邮件","utf-8"); String ip = Inet4Address.getLocalHost().getHostAddress(); String url = "http://"+ip+":8080/myxiaomi/activate?e="+ Base64Utils.encode(user.getEmail())+"&c="+Base64Utils.encode(user.getCode()); //设置邮件正文 setContent 可以使用html标签 message.setContent(user.getUsername()+",你好欢迎注册小米商城! 请点击链接进行激活:"+url+"","text/html;charset=utf-8"); //设置邮件的发送时间 是立即发送 message.setSentDate(new Date()); //保存设置 message.saveChanges(); } catch (UnsupportedEncodingException | MessagingException | UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } return message; }}
public class MD5Utils { public static String md5(String str) { try { MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(str.getBytes("utf-8")); byte[] digest = messageDigest.digest(); //1表示正数 BigInteger bigInteger = new BigInteger(1, digest); return bigInteger.toString(16); } catch (Exception e) { e.printStackTrace(); } return null; }}
public class Md5Util { public static final String SIGN_KEY = "sign_key";//签名key public static final String PARAMETER_KEY = "parameter_key";//拼装的参数key /** * 新的md5签名,首尾放secret。 * * @param key 商家key * tradeNo 流水号 * secret * @param key 分配给您的APP_SECRET */ public static String md5Signature(long id, String tradeNo, String key) { StringBuffer sb = new StringBuffer(); sb.append(key); sb.append(id); sb.append(tradeNo); sb.append(key); MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } String result = null; try { result = byte2hex(md.digest(sb.toString().getBytes("utf-8"))); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return result; } /** * 二行制转字符串 */ private static String byte2hex(byte[] b) { StringBuffer hs = new StringBuffer(); String stmp = ""; for (int n = 0; n < b.length; n++) { stmp = (Integer.toHexString(b[n] & 0XFF)); if (stmp.length() == 1) hs.append("0").append(stmp); else hs.append(stmp); } return hs.toString().toUpperCase(); } /*** * 对请求的参数排序,生成定长的签名 * @param paramsMap 排序后的字符串 * @param secret 密钥 * */ public static String md5Signature(MapparamsMap, String secret) { Map resultMap = new HashMap ();//用于记录返回的签名和将参数按照签名拼装的url String result = ""; StringBuilder sb = new StringBuilder(); Map treeMap = new TreeMap (); treeMap.putAll(paramsMap); sb.append(secret); Iterator iterator = treeMap.keySet().iterator(); while (iterator.hasNext()) { String name = (String) iterator.next(); sb.append(name).append(treeMap.get(name)); } sb.append(secret); resultMap.put(PARAMETER_KEY, sb.toString()); try { MessageDigest md = MessageDigest.getInstance("MD5"); /**MD5加密,输出一个定长信息摘要*/ result = byte2hex(md.digest(sb.toString().getBytes("utf-8"))); } catch (Exception e) { throw new RuntimeException("sign error !"); } resultMap.put(SIGN_KEY, result); return result; } /** * Calculates the MD5 digest and returns the value as a 16 element * byte[]
. * * @param data Data to digest * @return MD5 digest */ public static byte[] md5(String data) { return md5(data.getBytes()); } /** * Calculates the MD5 digest and returns the value as a 16 element *byte[]
. * * @param data Data to digest * @return MD5 digest */ public static byte[] md5(byte[] data) { return getDigest().digest(data); } /** * Returns a MessageDigest for the givenalgorithm
. * * @param * @return An MD5 digest instance. * @throws RuntimeException when a {@link NoSuchAlgorithmException} is * caught */ static MessageDigest getDigest() { try { return MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } }}
public class StringUtils { public static boolean isEmpty(String str) { if (str == null || str.trim().length() == 0) { return true; } else { return false; } }}
public class Base64Utils { //base64编码 public static String encode(String msg){ return Base64.getEncoder().encodeToString(msg.getBytes()); } //base64解码 public static String decode(String msg){ return new String(Base64.getDecoder().decode(msg)); }}String password="abc";//密码明文String salt=UUID.randomUUID().toString();//盐Integer iter = 1000;//迭代次数String pwd = new Md5Hash(password, salt,iter).toString(); //md5加密String pwd = new Md5Hash(password, salt, iter).toBase64(); //加密后转base64String pwd = new Sha256Hash(password, salt, iter).toString();//sha256加密String pwd = new Sha256Hash(password, salt, iter).toBase64();//加密后转base64String pwd = new Sha512Hash(password, salt, iter).toString();//sha256加密String pwd = new Sha512Hash(password, salt, iter).toBase64()//加密后转base64
public class DataSourceUtils { private static DruidDataSource dataSource; private static ThreadLocalthreadLocal; static { //实例化本地线程,但是为空 threadLocal = new ThreadLocal<>(); Properties properties = new Properties(); InputStream is = DataSourceUtils.class.getClassLoader().getResourceAsStream("druid.properties"); try { properties.load(is); dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties); } catch (Exception e) { e.printStackTrace(); System.out.println("初始化连接池失败"); } } public static DataSource getDataSource() { return dataSource; } public static Connection getConnection() { //获取连接 Connection connection = threadLocal.get(); //第一次获取,连接肯定是空的,这时需要绑定连接 if (connection == null) { try { connection = dataSource.getConnection(); } catch (SQLException e) { e.printStackTrace(); } threadLocal.set(connection);//绑定连接 } return connection; //返回同一个线程,即同一个连接 } //开启事务处理 public static void beginTranscation() { Connection connection = getConnection(); try { connection.setAutoCommit(false); } catch (SQLException e) { e.printStackTrace(); } } //提交事务 public static void commit() { Connection connection = getConnection(); try { connection.commit(); } catch (SQLException e) { e.printStackTrace(); } } //回滚 public static void rollBack() { Connection connection = getConnection(); try { connection.rollback(); } catch (SQLException e) { e.printStackTrace(); } } //事务关闭 public static void close() { Connection connection = getConnection(); try { connection.close(); threadLocal.remove();//解除绑定 } catch (SQLException e) { e.printStackTrace(); } }}
//生成令牌,单例模式public class TokenProccessor { private static final TokenProccessor INSTANCE = new TokenProccessor(); private TokenProccessor(){ } public static TokenProccessor getInstance() { return INSTANCE; } //生产令牌方法 public String makeToken() { //日期字符串+随机数=加密令牌 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS"); String str = sdf.format(new Date())+ new Random().nextInt(999999999); //Md5加密过程 try { //1. 获取消息摘要,传入md5加密算法 MessageDigest md5 = MessageDigest.getInstance("md5"); //2. 更新数据 md5.update(str.getBytes()); //3. 加密处理,得出字节结果 byte[] digest = md5.digest(); //4. 转字符串,用Base64编码,调取编码器 return Base64.getEncoder().encodeToString(digest); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; }}
//将令牌给到session,以及删除令牌public class TokenTools { public static void createToke(HttpServletRequest request, String tokenKey) { //1.获取token String token = TokenProccessor.getInstance().makeToken(); //上面的方法 request.getSession().setAttribute(tokenKey, token); //tokenKey是令牌名称 } public static void removeToke(HttpServletRequest request, String tokenKey) { //2.删除token request.getSession().removeAttribute(tokenKey); }}
三种方法:
public class UploadUtils { /*UUID的打印结果是有横杆的,需要去掉横杠,并用下划线与图片文件名连接*/ /*这样就可以生成一个不重复的图片名称,避免图片覆盖*/ public static String createNewFilename(String filename) { String s = UUID.randomUUID().toString().replace("-", ""); return s + "_" + filename; } /** * @param realpath 真实路径,这里是upload文件夹,但是不能将所有文件都存到该文件夹,需要分散 * @param filename 文件名称,可以获取其哈希值,然后取后四位,即0-15(0000-1111)随机数,作为一级子文件夹 * 然后将哈希值右移四位,取次后四位,还是0-15,作为二级文件夹,这样分散处理 * 这里返回的是文件夹的路径,所以需要在controller层将文件通过【File.separator】添加到路径 */ public static String createNewPath(String realpath, String filename) { int hashCode = filename.hashCode(); //32位 int dir1 = hashCode&0xf; //得到后四位0-15 int dir2 = (hashCode>>4)&0xf; //或者是 (hashCode&0xf0)>>4,获取次4位 0-15 String newPath = realpath + File.separator + dir1 + File.separator + dir2; File file = new File(newPath); if (!file.exists()) { file.mkdirs(); } return newPath; } /*遍历,用key保存真实文件名,带有UUID的文件名,用value保存没有UUID的文件名,显示是不带UUID,视觉好看,然后下载是带UUID*/ public static void listFiles(File dir, HashMapmap) { File[] files = dir.listFiles(); if (files != null) { for (File file : files) { if (file.isDirectory()) { listFiles(file, map); } else { map.put(file.getName(), file.getName().split("_")[1]); } } } }}
/** * 算术验证码 */public class Captcha1 { public static void generateCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException { BufferedImage bi = new BufferedImage(68, 22, BufferedImage.TYPE_INT_RGB); Graphics g = bi.getGraphics(); Color c = new Color(200, 150, 255); g.setColor(c); g.fillRect(0, 0, 68, 22); char[] op = "+-".toCharArray(); Random r = new Random(); int index, len1 = op.length; int result = 0, firstNum = 0, secondNum = 0; char operation = '0'; String ex=""; for (int i = 0; i < 4; i++) { // 四次循环,最后生成 【数字1 运算符 数字2 等号】四个部分,如【1 + 2 =】 if (i != 1) index = r.nextInt(100); else index = r.nextInt(len1); g.setColor(new Color(r.nextInt(88), r.nextInt(188), r.nextInt(255))); if (i == 0) { //g.drawString(index+"", (i*15)+3, 18); ex+=index+" "; firstNum = index; } else if (i == 2) { //g.drawString(index+"", (i*15)+3, 18); ex+=index+" "; secondNum = index; } else if (i == 1) { //g.drawString(op[index]+"", (i*15)+3, 18); ex+=op[index]+" "; operation = op[index]; } else { //g.drawString("=", (i*15)+3, 18); ex+="="; } } // 绘制算术表达式:ex g.drawString(ex,3,18); // 计算结果 if (operation == '+') result = firstNum+secondNum; else if (operation == '-') result = firstNum-secondNum; else if (operation == '*') result = firstNum*secondNum; // 结果存入session request.getSession().setAttribute("captcha", result); // 写出验证码( 响应请求 ) response.setDateHeader("Expires", 0L); response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); response.addHeader("Cache-Control", "post-check=0, pre-check=0"); response.setHeader("Pragma", "no-cache"); // 指向客户端的输出流 ServletOutputStream out = response.getOutputStream(); // 写出验证码图片,响应 ImageIO.write(bi, "JPG", out); try { out.flush(); } finally { out.close(); } }}
/** * simple验证码 */public class Captcha2 { public static void generateCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException { BufferedImage bi = new BufferedImage(68, 22, BufferedImage.TYPE_INT_RGB); Graphics g = bi.getGraphics(); Color c = new Color(200, 150, 255); g.setColor(c); g.fillRect(0, 0, 68, 22); char[] ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();//字符集合 Random r = new Random(); int len = ch.length, index; StringBuffer sb = new StringBuffer(); for (int i = 0; i < 4; i++) { //验证码长度 index = r.nextInt(len); g.setColor(new Color(r.nextInt(88), r.nextInt(188), r.nextInt(255))); g.drawString(ch[index]+"", (i*15)+3, 18); sb.append(ch[index]); } //存入session request.getSession().setAttribute("captcha", sb.toString()); // 写出验证码( 响应请求 ) response.setDateHeader("Expires", 0L); response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); response.addHeader("Cache-Control", "post-check=0, pre-check=0"); response.setHeader("Pragma", "no-cache"); ServletOutputStream out = response.getOutputStream(); ImageIO.write(bi, "JPG", out); try { out.flush(); } finally { out.close(); } }}
该工具类使用注意事项:
public class AutoCookie { public static void loginCookie(String key, String value, HttpServletResponse response) { Cookie cookie = new Cookie(key, value); cookie.setHttpOnly(true); cookie.setPath("/"); cookie.setMaxAge(60*60*24); response.addCookie(cookie); } public static void logoutCookie(String key, HttpServletResponse response) { Cookie cookie = new Cookie(key, ""); cookie.setHttpOnly(true); cookie.setPath("/"); cookie.setMaxAge(0); response.addCookie(cookie); }}
外部需要ajax请求获取,会直接将其转为js对象,直接使用msg或者code属性即可。
最后的可以使用其中的put方法,该方法可以链式调用,将多个参数封装 R.ok().put....
public class R extends HashMap{ private int code;//0 操作成功 1 操作失败 private String msg; public R(){ } public R(int code){ //this.code=code; this.put("code",code); } public R(int code, String msg){ super.put("code",code); super.put("msg",msg); } public static R ok(){ return new R(0); } public static R ok(String msg){ return new R(0,msg); } public static R error(){ return new R(1); } public static R error(String msg){ return new R(1,msg); } public R put(String key,Object o){ super.put(key,o); return this; }}
转换工具类JackSon
public class JacksonUtil { /** * 对象转json */ public static String obj2json(Object obj) { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(Include.NON_NULL); // 忽略空属性 String json = null; try { json = mapper.writeValueAsString(obj); } catch (Exception e) { LOGGER.error("", e); } return json; } /** * json转对象(支持深度嵌套) */ public staticT jsonToObj(String json, TypeReference typeReference) { if (StringUtils.isBlank(json)) { return null; } ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); T t = null; try { t = mapper.readValue(json, typeReference); } catch (Exception e) { LOGGER.error("", e); } return t; } /** * json转对象 */ public static T json2Obj(String json, Class clazz) { if (StringUtils.isBlank(json)) { return null; } ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); T t = null; try { t = mapper.readValue(json, clazz); } catch (Exception e) { LOGGER.error("", e); } return t; } /** * json转list */ public static List json2List(String json, Class clazz) { ObjectMapper mapper = new ObjectMapper(); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); JavaType javaType = getCollectionType(mapper, ArrayList.class, clazz); List t = new ArrayList (); try { t = (List ) mapper.readValue(json, javaType); } catch (Exception e) { LOGGER.error("", e); } return t; } /** * json转为map */ public static HashMap jsonToMap(String json, Class class1, Class class2) { ObjectMapper mapper = new ObjectMapper(); HashMap map = null; try { JavaType javaType = mapper.getTypeFactory().constructParametricType(HashMap.class, class1, class2); map = mapper.readValue(json, javaType); } catch (Exception e) { LOGGER.error("", e); } return map; }}
public class MyResolver implements HandlerExceptionResolver{ private MapevMapping=new HashMap(); private final String DEFAULT_ERROR="error"; public MyResolver(){ evMapping.put(UnauthenticatedException.class,"redirect:/user/login"); evMapping.put(UnauthorizedException.class,"error"); evMapping.put(IncorrectCredentialsException.class,"json:用户名或密码错误"); evMapping.put(UnknownAccountException.class,"json:用户名或密码错误"); } @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { ModelAndView mv = new ModelAndView(); // 开发时必备的 ex.printStackTrace(); String view = evMapping.get(ex.getClass()); if(view == null){ view = DEFAULT_ERROR; } mv.setViewName(view); if(view.startsWith("json:")){ //System.out.println("未知账户"); writeJson(response,view); mv=null; } return mv; } private void writeJson(HttpServletResponse response,String view){ response.setContentType("application/json;charset=utf-8"); PrintWriter writer = null; try { writer = response.getWriter(); } catch (IOException e) { e.printStackTrace(); } writer.print(JSON.toJSON(R.error(view.substring(5)))); writer.close(); }}
/** * ApplicationContexUtil * 如果一个类是 ApplicationContextAware的子类 * 则其setApplicationContext会被系统调用,可以接受到当前的工厂对象 */@Componentpublic class ApplicationContextUtil implements ApplicationContextAware{ private static ApplicationContext context; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { context=applicationContext; } public static Object getBean(String beanName){ return context.getBean(beanName); }}
解锁定时任务,该任务可以加入到动态任务中
public class UnLockJob implements Job{ //private Logger log = LoggerFactory.getLogger(UnLockJob.class); //private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(UnLockJob.class); /** * 检查用户是否需要解锁 * @param context * @throws JobExecutionException */ public void execute(JobExecutionContext context) throws JobExecutionException { SysUserService userService = (SysUserService) ApplicationContextUtil.getBean("sysUserService"); Listusers = userService.querySysUsers(); for (SysUser user : users) { log.debug("用户状态:"+user.getStatus()); System.out.println("用户状态:"+user.getStatus()); if(user.getStatus()==0){ log.debug("用户:"+user.getUsername()+" 被发现了是锁定状态"); // 获取当天 日期 Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date()); int i = calendar.get(Calendar.MINUTE); // 获取锁定 日期 Calendar calendar2 = Calendar.getInstance(); calendar2.setTime(user.getLockdate()); int j = calendar2.get(Calendar.MINUTE); if(i>j){ //锁定期到,解锁 log.debug("用户:"+user.getUsername()+" 锁定到期"); userService.unlockUser(user.getUserId()); } } } }}
public class FileInterceptor implements HandlerInterceptor { @Setter private long fileSize; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { ServletRequestContext src = new ServletRequestContext(request); long realSize = src.contentLength(); if (fileSize >= realSize) { return true; } response.sendRedirect(request.getContextPath() + "/fileError.jsp"); return false; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { }}
//导入依赖org.apache.commons commons-lang3 commons-fileupload commons-fileupload commons-beanutils commons-beanutils org.apache.poi poi //工具类代码public class ExcelUtil { private static final Logger LOGGER = LoggerFactory.getLogger(LogNameEnums.SERVICE_LOG.getLogName()); /** * 根据文件类型读取文件 */ public static ArrayList org.apache.poi poi-ooxml readFileByWay(String file) { ArrayList list = new ArrayList (); Workbook workbook = null; InputStream is = null; try { is = new FileInputStream(file); if (file.endsWith("xls")) { workbook = new HSSFWorkbook(is); } else if (file.endsWith("xlsx")) { workbook = new XSSFWorkbook(is); } Sheet sheet = workbook.getSheetAt(0); int firstRowIndex = sheet.getFirstRowNum(); int lastRowIndex = sheet.getLastRowNum(); int totalCells = 0;// 列 if (lastRowIndex >= 1 && sheet.getRow(0) != null) { totalCells = sheet.getRow(0).getPhysicalNumberOfCells();// 获取列 for (int rowIndex = firstRowIndex + 1; rowIndex <= lastRowIndex; rowIndex++) { Row currentRow = sheet.getRow(rowIndex);// 当前行 String[] cellStrs = new String[totalCells]; for (int c = 0; c < totalCells; c++) { cellStrs[c] = getCellValue(currentRow.getCell(c), true); } list.add(cellStrs); } } } catch (Exception e) { LOGGER.error("",e); } finally { if (is != null) { try { is.close(); } catch (IOException e) { LOGGER.error("",e); } } } return list; } /** * 根据文件类型读取文件 */ public static ArrayList readFileByWay(String file, int firstRowIndex) { ArrayList list = new ArrayList (); Workbook workbook = null; InputStream is = null; try { is = new FileInputStream(file); if (file.endsWith("xls")) { workbook = new HSSFWorkbook(is); } else if (file.endsWith("xlsx")) { workbook = new XSSFWorkbook(is); } Sheet sheet = workbook.getSheetAt(0); int lastRowIndex = sheet.getLastRowNum(); int totalCells = 0;// 列 if (lastRowIndex >= 1 && sheet.getRow(0) != null) { totalCells = sheet.getRow(firstRowIndex).getPhysicalNumberOfCells();// 获取列 for (int rowIndex = firstRowIndex + 1; rowIndex <= lastRowIndex; rowIndex++) { Row currentRow = sheet.getRow(rowIndex);// 当前行 String[] cellStrs = new String[totalCells]; for (int c = 0; c < totalCells; c++) { cellStrs[c] = getCellValue(currentRow.getCell(c), true); } list.add(cellStrs); } } } catch (Exception e) { LOGGER.error("",e); } finally { if (is != null) { try { is.close(); } catch (IOException e) { LOGGER.error("",e); } } } return list; } /** * 根据文件类型读取文件 */ public static ArrayList readFileByWay(MultipartFile file, int firstRowIndex) { ArrayList list = new ArrayList (); Workbook workbook = null; InputStream is = null; try { is = file.getInputStream(); CommonsMultipartFile c_file = (CommonsMultipartFile) file; String fileName = c_file.getFileItem().getName(); if (fileName.endsWith("xls")) { workbook = new HSSFWorkbook(is); } else if (fileName.endsWith("xlsx")) { workbook = new XSSFWorkbook(is); } Sheet sheet = workbook.getSheetAt(0); int lastRowIndex = sheet.getLastRowNum(); int totalCells = 0;// 列 if (lastRowIndex >= 1 && sheet.getRow(0) != null) { totalCells = sheet.getRow(firstRowIndex - 1).getPhysicalNumberOfCells();// 获取列 for (int rowIndex = firstRowIndex; rowIndex <= lastRowIndex; rowIndex++) { Row currentRow = sheet.getRow(rowIndex);// 当前行 String[] cellStrs = new String[totalCells]; for (int c = 0; c < totalCells; c++) { cellStrs[c] = getCellValue(currentRow.getCell(c), true); } list.add(cellStrs); } } } catch (Exception e) { LOGGER.error("",e); } finally { if (is != null) { try { is.close(); } catch (IOException e) { LOGGER.error("",e); } } } return list; } /** * 取单元格的值 */ private static String getCellValue(Cell cell, boolean treatAsStr) { if (cell == null) { return ""; } if (treatAsStr) { // 数字文本还被读错,临时把它当做文本来读取 cell.setCellType(Cell.CELL_TYPE_STRING); } if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) { return String.valueOf(cell.getBooleanCellValue()).trim(); } else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) { return String.valueOf(cell.getNumericCellValue()).trim(); } else { return String.valueOf(cell.getStringCellValue()).trim(); } } /** * 创建excel */ public static HSSFWorkbook createExcel(String filename, String title, String[] secondTitles, List > list, HttpServletRequest request, HttpServletResponse response) { HSSFWorkbook book = new HSSFWorkbook(); LOGGER.info("list size:" + list.size()); int totle = list.size();// 获取List集合的size int mus = 65530;// 每个工作表格最多存储2条数据(注:excel表格一个工作表可以存储65536条) int avg = totle / mus; for (int m = 0; m < avg + 1; m++) { HSSFSheet sheet = book.createSheet(title + m); sheet.setDisplayGridlines(true); // 定义各种样式 HSSFCellStyle firStyle = createMyCellStyle(book, 18, true, true, true, null);// 大标题 // 第一行样式 // HSSFCellStyle secStyle = createMyCellStyle(book, 12, true, false, // true, null);// 中标题 // 第二、三行样式 HSSFCellStyle thirStyle = createMyCellStyle(book, 10, true, true, true, null);// 小标题 // 第四行样式 HSSFCellStyle contentStyle = createMyCellStyle(book, 10, false, true, true, "宋体");// 内容 HSSFRow row = null; // 第一行 int index = 0; @SuppressWarnings("unused") SimpleDateFormat ss = new SimpleDateFormat("yyyy年MM月dd日"); row = sheet.createRow(index); row.setHeight((short) 600); createCellAndSetStrVal(row, 0, firStyle, title); sheet.addMergedRegion(new CellRangeAddress(index, index, (short) 0, (short) (secondTitles.length - 1))); LOGGER.info("生成大标题"); index++; // 第三行 row = sheet.createRow(index); row.setHeight((short) 1200); for (int i = 0; i < secondTitles.length; i++) { createCellAndSetStrVal(row, i, thirStyle, secondTitles[i]); } index++; List > newlist = new ArrayList >(); int num = m * mus; for (int x = num; x < num + mus; x++) { if (x >= list.size()) { break; } newlist.add(list.get(x)); } for (LinkedList set : newlist) { row = sheet.createRow(index); row.setHeight((short) 400); createCellAndSetNumberVal(row, 0, contentStyle, String.valueOf(index - 2)); Iterator it = set.iterator(); int j = 1; while (it.hasNext()) { String content = (String) it.next(); if (content != null) { createCellAndSetStrVal(row, j++, contentStyle, content); } else { createCellAndSetStrVal(row, j++, contentStyle, ""); } } index++; } for (int i = 0; i < secondTitles.length; i++) { sheet.autoSizeColumn(i); } } export(filename, book, request, response); return book; } /** * 创建单元格式样 * @param workbook * @param fontHeight 字号 * @param isBold 是否粗体 * @param isAlignCenter 是否水平居中 * @param isVerticalCenter 是否垂直居中 * @param fontName 字体名称 * @return */ private static HSSFCellStyle createMyCellStyle(HSSFWorkbook workbook, int fontHeight, boolean isBold, boolean isAlignCenter, boolean isVerticalCenter, String fontName) { // 设置字体和样式 HSSFCellStyle style = workbook.createCellStyle(); style.setBorderBottom(HSSFCellStyle.BORDER_THIN); style.setBorderTop(HSSFCellStyle.BORDER_THIN); style.setBorderLeft(HSSFCellStyle.BORDER_THIN); style.setBorderRight(HSSFCellStyle.BORDER_THIN); if (isAlignCenter) { style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 水平居中 } if (isVerticalCenter) { style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直居中 } HSSFFont font = workbook.createFont(); if (fontName != null) { font.setFontName(fontName); } else { font.setFontName("微软雅黑"); } font.setColor(HSSFColor.BLACK.index); font.setFontHeightInPoints((short) fontHeight); if (isBold) { font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); } style.setFont(font); return style; } /** * 创建单元格并写入数字 * @param row 行 * @param num 列 * @param style 单元格式样 * @param value 单元格内容 */ private static void createCellAndSetNumberVal(HSSFRow row, int num, HSSFCellStyle style, String value) { HSSFCell cell = row.createCell(num); if (style != null) { cell.setCellStyle(style); } if (StringUtils.isNotBlank(value)) { cell.setCellValue(Double.parseDouble(value)); } } /** * 创建单元格并写入文本内容 * @param row 行 * @param num 列 * @param style 单元格式样 * @param value 单元格内容 */ private static void createCellAndSetStrVal(HSSFRow row, int num, HSSFCellStyle style, String value) { // HSSFCell cell = row.createCell((short) num); HSSFCell cell = row.createCell(num); if (style != null) { cell.setCellStyle(style); } if (StringUtils.isNotEmpty(value)) { HSSFRichTextString richstr = new HSSFRichTextString(value); cell.setCellValue(richstr); } } public static void export(String filename, HSSFWorkbook book, HttpServletRequest request, HttpServletResponse response) { try { // 输出流导出 OutputStream os; String agent = request.getHeader("User-Agent").toLowerCase(); if (agent.indexOf("firefox") > -1) { filename = new String(filename.getBytes(), "ISO8859-1");// firefox浏览器 } else if (agent.indexOf("msie") > -1) { filename = URLEncoder.encode(filename, "UTF-8");// IE浏览器 } else if (agent.indexOf("chrome") > -1) { filename = URLEncoder.encode(filename, "UTF-8");// chrome谷歌 } else { filename = URLEncoder.encode(filename, "UTF-8");// 其他(包括360) } response.reset(); response.setContentType("application/msexcel"); response.setHeader("Content-Disposition", "attachment;" + " filename=" + filename); os = response.getOutputStream(); book.write(os); os.flush(); os.close(); } catch (Exception e) { LOGGER.error("",e); } }
private ListgetEsDataByPage(int pageNo, int pageSize, AvApiQueryStatisticDO queryBean){ BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); boolQueryBuilder.must(QueryBuilders.termQuery("agencyCode", queryBean.getAgencyCode())); boolQueryBuilder.must(QueryBuilders.termQuery("queryDate", queryBean.getQueryDate())); Client client = es.getClient(); SearchRequestBuilder searchRequestBuilder = client.prepareSearch(EsIndexTypeEnum.QF_AV_API_QUERY_REQUEST_STATISTIC_BURYPOINT.getIndex()) .setTypes(EsIndexTypeEnum.QF_AV_API_QUERY_REQUEST_STATISTIC_BURYPOINT.getType()) .setQuery(boolQueryBuilder); SearchResponse searchResponse = getSearchResponse(client, searchRequestBuilder, pageNo, pageSize); return getEsDataBySearchResponse(searchResponse); } private SearchResponse getSearchResponse(Client client, SearchRequestBuilder searchRequestBuilder, int page, int pageSize) { SearchResponse response;//大于10000条数据使用滚动查询 if ((page * pageSize) <= DEFAULT_QUERY_ES_SIZE) { LOGGER.info(new StringBuilder("Es一般查询: page = ").append(page).append(", pageSize = ").append(pageSize)); searchRequestBuilder.setFrom((page - 1) * pageSize).setSize(pageSize); //执行查询 response = searchRequestBuilder.execute().actionGet(); } else { LOGGER.info(new StringBuilder("Es深度scroll查询查询: page = ").append(page).append(", pageSize = ").append(pageSize)); //滚动过期时间(1s) TimeValue timeValue = TimeValue.timeValueMillis(1000); searchRequestBuilder.setSize(pageSize).setScroll(timeValue); response = searchRequestBuilder.execute().actionGet(); //记录第一次滚动id String scrollId = response.getScrollId(); for (int i = 1; i < page; i++) { SearchScrollRequestBuilder searchScrollRequestBuilder = client.prepareSearchScroll(scrollId); //重新设定滚动时间 searchScrollRequestBuilder.setScroll(timeValue); // 请求 response = searchScrollRequestBuilder.get(); scrollId = response.getScrollId(); } //清除滚动id ClearScrollRequestBuilder clearScrollRequestBuilder = client.prepareClearScroll(); clearScrollRequestBuilder.addScrollId(scrollId); clearScrollRequestBuilder.get(); } return response; }
转载地址:http://dpgzi.baihongyu.com/